var oParent=$('.ga_lt_content');
var iWidth=220;
var iSpeed=20;
var iOutWidth=iWidth+iSpeed;
var iCells= 0;
var sUrl = 'http://www.wookmark.com/api/json/popular?callback=?';
var iPage=0;
var arrL=[];
var arrT=[];
var iBtn=true;

function setCells(){
   iCells = Math.floor($(window).innerWidth()/iOutWidth);

   if (iCells < 3) {
        iCells = 3;
    } else if (iCells > 6) {
        iCells = 6;
    }

   //document.title=iCells;
   oParent.css('width',iOutWidth*iCells-iSpeed);
}

setCells();

for(var i=0;i<iCells;i++){
    arrT.push(0)
    arrL.push(i*iOutWidth)
};

getData();

function getData(){
    if(iBtn){
        iBtn=false;
        $.getJSON(sUrl,'page='+iPage,function(data){
            //console.log(data)
            $.each(data,function(index,val){
                var aDivWrap=$('<div class="img"></div>');
                var aImg=$('<img></img>');
                aImg.attr('src',val.preview);

                aDivWrap.append(aImg);
                oParent.append(aDivWrap);

                var iHeight= parseInt(iWidth/val.width*val.height);
                aImg.css({
                    width:iWidth,
                    height:iHeight
                });

                var iMinIndex=getMin();

                aDivWrap.css({
                    left:arrL[iMinIndex],
                    top:arrT[iMinIndex]
                });
                arrT[iMinIndex]+=iHeight+100;
                iBtn=true;
            });
        });
    };
    
};

$(window).on('scroll',function(){
    var iH=$(window).scrollTop()+$(window).innerHeight();
    var iMinIndex=getMin();
    if(arrT[iMinIndex]<iH){
        iPage++;
        getData();
    }
});

function getMin(){
    var iv=arrT[0];
    var _index=0;
    for(var i=0;i<arrT.length;i++){
        if(arrT[i]<iv){
            iv=arrT[i];
            _index=i;
        };
    };
    return _index;
};